<template>
  <div class="mod-poi-main">
    <div class="search-bar">
      <el-form
        @submit.native.prevent
        :inline="true"
        ref="searchForm"
        :model="searchForm"
        size="small"
        :class="
          this.$i18n.t('language') === 'English'
            ? 'en-search-form'
            : 'zh-search-form'
        "
      >
        <div class="input-row">
          <el-form-item :label="$t('outlet.outletId') + ':'">
            <el-input
              v-model="searchForm.shopCode"
              size="small"
              :placeholder="$t('tip.input')"
            ></el-input>
          </el-form-item>

          <el-form-item prop="shopName" :label="$t('outlet.outletName') + ':'">
            <el-input
              v-model="searchForm.shopName"
              size="small"
              :placeholder="$t('outlet.outletName')"
            ></el-input>
          </el-form-item>

          <!-- <el-form-item :label="$t('outlet.shopAppName') + ':'">
            <el-input
              v-model="searchForm.shopAppName"
              size="small"
              :placeholder="$t('tip.input')"
            ></el-input>
          </el-form-item> -->

          <el-form-item style="float: right">
            <div class="default-btn primary-btn" @click="searchChange(true)">
              {{ $t("product.search") }}
            </div>
            <div class="default-btn" @click="resetSearchForm('searchForm')">
              {{ $t("product.reset") }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <!-- <el-checkbox
          v-model="selectAll"
          @change="handleSelectAll"
          class="all-check-btn"
          v-if="dataList.length"
          >{{ $t("publics.selectAll") }}</el-checkbox
        > -->
        <div class="default-btn primary-btn" @click.stop="importDateHandle()">
          {{ $t("crud.importe") }}
        </div>
        <!-- <div
          :class="[
            dataListSelections.length <= 0 ? 'disabled-btn' : '',
            'default-btn',
          ]"
          @click="exportExcel()"
        >
          {{ $t("crud.excelBtn") }}
        </div> -->
      </div>
      <div class="table-con banner-table">
        <template>
          <el-table
            ref="bannerListTable"
            :data="dataList"
            header-cell-class-name="table-header"
            row-class-name="table-row"
            @selection-change="handleSelectionChange"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              :label="$t('formData.serialNumber')"
              prop="index"
              align="center"
            />
            <!-- <el-table-column type="selection" v-if="dataList.length" /> -->
            <el-table-column
              prop="shineiId"
              align="center"
              :label="$t('outlet.outletId')"
            >
            </el-table-column>
            <el-table-column align="center" :label="$t('outlet.outletName')">
              <template slot-scope="scope">
                {{ scope.row.poiName }}
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              :label="$t('shopProcess.shopAffiliatingArea')"
              width="200"
            >
              <template slot-scope="scope">
                <div v-if="scope.row.canEdit">
                  <el-cascader
                    size="mini"
                    style="width: 100%"
                    v-model="
                      scope.row.airportShopAddressObj.airportShopAddressIds
                    "
                    ref="CascaderShopLocation"
                    :options="shopLocationOptions"
                    :props="shopLocationProps"
                    @change="handleShopLocationChange($event, scope.$index)"
                  >
                  </el-cascader>
                </div>
                <div v-else>
                  {{
                    scope.row.airportShopAddressObj.airportShopAddressNames
                      | format
                  }}
                </div>
              </template>
            </el-table-column>

            <el-table-column align="center" :label="$t('shopProcess.shopLng')">
              <template slot-scope="scope">
                <div v-if="scope.row.canEdit">
                  <el-input
                    v-model="scope.row.poiLnt"
                    onkeypress="return( /[\d.]/.test(String.fromCharCode(event.keyCode)))"
                    maxlength="30"
                    oninput="if(value.length > 30) value=value.slice(0, 30)"
                    size="mini"
                    type="number"
                  />
                </div>
                <div v-else>{{ scope.row.poiLnt }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('shopProcess.shopLat')">
              <template slot-scope="scope">
                <div v-if="scope.row.canEdit">
                  <el-input
                    v-model="scope.row.poiLat"
                    onkeypress="return( /[\d.]/.test(String.fromCharCode(event.keyCode)))"
                    oninput="if(value.length > 30) value=value.slice(0, 30)"
                    maxlength="30"
                    size="mini"
                    type="number"
                  />
                </div>
                <div v-else>{{ scope.row.poiLat }}</div>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              :label="$t('publics.operating')"
            >
              <template slot-scope="scope">
                <div class="text-btn-con">
                  <div
                    v-if="!scope.row.canEdit"
                    class="default-btn text-btn"
                    @click="editDateHandle(scope.$index)"
                  >
                    {{ $t("user.editBtn") }}
                  </div>
                  <div
                    class="default-btn text-btn"
                    v-if="scope.row.canEdit"
                    @click="updateRowDateHandle(scope.$index, scope.row)"
                  >
                    {{ $t("sys.affirm") }}
                  </div>
                  <div
                    class="default-btn text-btn"
                    style="color: #999"
                    v-if="scope.row.canEdit"
                    @click="editDateHandle(scope.$index, false)"
                  >
                    {{ $t("crud.cancelBtn") }}
                  </div>
                  <!-- <div
                    class="default-btn text-btn"
                    @click="deleteHandle(scope.row.id)"
                  >
                    {{ $t("user.deleteBtn") }}
                  </div> -->
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <el-pagination
        v-if="dataList.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <ExcelPoiImport
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="refreshChange"
    ></ExcelPoiImport>
  </div>
</template>

<script>
import ExcelPoiImport from "./excel-poi-import";
import { deepCopy } from "@/utils";
export default {
  data() {
    return {
      currentHandleItem: {},
      dateRange: [],
      theData: {}, // 保存上次点击查询的请求条件
      dataList: [],
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      // 修改
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      searchForm: {
        status: "",
      },
      selectAll: false,
      activeTabIndex: "1",
      shopLocationOptions: [],
      shopLocationProps: {
        label: "name",
        value: "id",
      },
    };
  },
  components: {
    ExcelPoiImport,
  },
  filters: {
    format(val) {
      if (!val) return;
      return val.join("-");
    },
  },
  created() {
    this.getDataList();
    this.queryShopLocation();
  },
  methods: {
    changeDateRange(e) {
      if (e) {
        this.searchForm.startTime = e[0];
        this.searchForm.endTime = e[1];
      } else {
        delete this.searchForm.startTime;
        delete this.searchForm.endTime;
      }
    },
    tabChange(e) {
      this.dataList = [];
      console.log(this.activeTabIndex);
      if (this.activeTabIndex == 1) {
        delete this.searchForm.processStatus;
      } else {
        this.searchForm.processStatus = 0;
      }
      this.getDataList(1, true);
    },
    handlePicError(event) {
      event.target.src = require("@/assets/img/def.png");
    },
    /**
     * 获取图片路径
     */
    getImgSrc(img) {
      if (!img) {
        return "";
      }
      if (img.indexOf("http://") === 0 || img.indexOf("https://") === 0) {
        return img;
      }
      return this.resourcesUrl + img;
    },
    queryShopLocation() {
      this.$http({
        url: this.$http.adornUrl("/admin/platform/airportStation/list"),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.shopLocationOptions = data;
      });
    },
    handleShopLocationChange(e, index) {
      let airportShopAddressObj = {
        airportShopAddressIds: [],
        airportShopAddressNames: [],
      };
      let nodes = this.$refs.CascaderShopLocation.getCheckedNodes(true);
      // 反转数组
      let reverseNames = [];
      let node = nodes[0];
      while (node.parent) {
        reverseNames.push(node.label);
        node = node.parent;
      }
      reverseNames.push(node.label);
      airportShopAddressObj.airportShopAddressNames = reverseNames.reverse();
      airportShopAddressObj.airportShopAddressIds = e;
      console.log(airportShopAddressObj);
      this.$set(
        this.dataList[index],
        "airportShopAddressObj",
        airportShopAddressObj
      );
      this.$set(
        this.dataList[index],
        "airportShopAddress",
        JSON.stringify(airportShopAddressObj)
      );
    },
    // 获取数据列表
    getDataList(page, newData = false) {
      if (this.page) {
        let size = Math.ceil(this.page.total / this.page.pageSize);
        this.page.currentPage =
          (this.page.currentPage > size ? size : this.page.currentPage) || 1;
      }
      this.dataListLoading = true;
      if (newData || !this.theData) {
        this.theData = JSON.parse(JSON.stringify(this.searchForm));
      }

      this.$http({
        url: this.$http.adornUrl("/platform/shopDetail/poi/getShopPoiList"),
        method: "post",
        params: this.$http.adornParams(
          Object.assign(
            {
              current: page == null ? this.page.currentPage : page.currentPage,
              size: page == null ? this.page.pageSize : page.pageSize,
              imgType: 2,
            },
            this.theData
          )
        ),
      }).then(({ data }) => {
        this.dataList = data.records.map((m) => {
          m.imgUrl = this.getImgSrc(m.imgUrl);
          if (!m.airportShopAddressObj) {
            m.airportShopAddressObj = {
              airportShopAddressIds: [],
              airportShopAddressNames: [],
            };
          }
          return m;
        });
        this.page.total = data.total;
        this.dataListLoading = false;
      });
    },
    exportExcel(e) {
      // 导出
    },

    editDateHandle(index, canEdit = true) {
      if (canEdit) {
        this.dataList[index]._oldRow = deepCopy(this.dataList[index]);
      } else {
        let item = deepCopy(this.dataList[index]._oldRow);
        this.$set(this.dataList, index, item);
      }
      this.$set(this.dataList[index], "canEdit", canEdit);
    },
    updateRowDateHandle(index, row) {
      if (
        row.airportShopAddressObj &&
        row.airportShopAddressObj.airportShopAddressIds &&
        row.airportShopAddressObj.airportShopAddressIds.length
      ) {
        row.addressId =
          row.airportShopAddressObj.airportShopAddressIds[
            row.airportShopAddressObj.airportShopAddressIds.length - 1
          ];
      }
      this.$http({
        url: this.$http.adornUrl("/platform/shopDetail/poi/updateShopPoi"),
        method: "post",
        data: this.$http.adornData(row),
      }).then(({ code }) => {
        if (code == "00000") {
          this.$set(this.dataList[index], "canEdit", false);
          this.$message({
            message: this.$i18n.t("publics.operation"),
            type: "success",
            duration: 1500,
          });
        } else {
          this.searchChange(true);
        }
      });
    },

    // 新增
    importDateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id, { imgType: 2 });
      });
    },
    // 删除
    // deleteHandle(id) {
    //   let ids = id
    //     ? [id]
    //     : this.dataListSelections.map((item) => {
    //         return item.imgId;
    //       });
    //   if (!id && !this.dataListSelections.length) {
    //     return;
    //   }
    //   let tip =
    //     this.$i18n.t("remindPop.makeSure") +
    //     "[" +
    //     (id
    //       ? this.$i18n.t("remindPop.delete")
    //       : this.$i18n.t("remindPop.batchDeletion"));
    //   tip = tip + "]" + this.$i18n.t("remindPop.operation") + "?";
    //   this.$confirm(tip, this.$i18n.t("remindPop.remind"), {
    //     confirmButtonText: this.$i18n.t("remindPop.confirm"),
    //     cancelButtonText: this.$i18n.t("remindPop.cancel"),
    //     type: "warning",
    //   }).then(() => {
    //     this.$http({
    //       url: this.$http.adornUrl("/platform/indexImg"),
    //       method: "delete",
    //       data: this.$http.adornData(ids, false),
    //     }).then(({ data }) => {
    //       this.page.total = this.page.total - ids.length;
    //       this.$message({
    //         message: this.$i18n.t("publics.operation"),
    //         type: "success",
    //         duration: 1500,
    //         onClose: () => {
    //           this.handleSelectAll();
    //           this.refreshChange();
    //         },
    //       });
    //     });
    //   });
    // },
    // 条件查询
    searchChange(newData = false) {
      this.page.currentPage = 1;
      this.getDataList(this.page, newData);
    },
    // 刷新回调
    refreshChange() {
      this.getDataList(this.page);
    },
    // 多选变化
    handleSelectionChange(val) {
      this.dataListSelections = val;
      this.selectAll = val.length === this.dataList.length;
    },
    /**
     * 全选按钮
     */
    handleSelectAll() {
      if (this.$refs.bannerListTable.selection.length < this.dataList.length) {
        this.selectAll = true;
      } else {
        this.selectAll = false;
      }
      this.$refs.bannerListTable.toggleAllSelection();
    },

    /**
     * 重置表单
     * @param {String} formName 表单名称
     */
    resetSearchForm(formName) {
      this.$refs[formName].resetFields();
      this.dateRange = [];
      this.searchForm = {
        processStatus: this.searchForm.processStatus,
      };
      this.prodName = "";
      this.isTop = "";
      this.categoryId = null;
    },

    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getDataList();
    },
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.getDataList();
    },
  },
};
</script>

<style scoped>
::v-deep .el-table__fixed-right {
  height: 98% !important;
}

::v-deep .el-table__fixed-right::before {
  background-color: transparent;
}

::v-deep .el-table::before {
  z-index: 6;
}
</style>
